package com.example.covid19.controllers;


import com.example.covid19.models.RegionStates;
import com.example.covid19.services.Covid19DataService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequiredArgsConstructor
public class homeController {
    @Resource
    private final Covid19DataService data;
    private int num=10;
    @RequestMapping(value = "/")
    public String show(@RequestParam(value = "country",required = false) String country, @RequestParam(value = "page",required=false) String page, Model model) {
        List<RegionStates> allStates;
        if(country == null || country.equals("all")||country.equals(""))
            allStates=data.getAllRegionStates();
        else
            allStates=data.getAllRegionStates()
                    .parallelStream()
                    .filter(RegionStates->RegionStates.getCountry().equals(country))
                    .collect(Collectors.toList());
        allStates=selectStates(page,allStates,model);
        model.addAttribute("RegionStatesLists",allStates);
        if(country==null||country.equals(""))
            model.addAttribute("country","all");
        else
            model.addAttribute("country",country);
        return "show";
    }
    public List<RegionStates> selectStates(String page,List<RegionStates> allStates,Model model){
        int currentPage=1;
        int maxPage=allStates.size()/num+1;
        List<RegionStates> showStates=new ArrayList<>();
        if(page!=null)
            currentPage=Integer.parseInt(page);
        if(currentPage<=0)
            currentPage=1;
        if(currentPage>maxPage)
            currentPage=maxPage;
        int start=(currentPage*num-num)>allStates.size()?((currentPage-1)*num-num):(currentPage*num-num);
        int end=start+num;
        while(start<end&&start<allStates.size()){
            showStates.add(allStates.get(start));
            start++;
        }
        model.addAttribute("lastpage",maxPage);
        model.addAttribute("currentpage",currentPage);
        return showStates;
    }
}
